<template>
  <div>
    <el-card shadow="hover">
    <el-form ref="formRef" :model="state.articleForm" :rules="rules" size="default" label-width="300px">
        <el-form-item label="文章标题" prop="title">
          <el-input
              v-model="state.articleForm.title"
              placeholder="请输入标题名称"
              style="width: 40%"
              type="textarea"
              rows="2"
          />
        </el-form-item>

        <el-form-item label="文章头图" prop="titleUrl">
          <el-upload
              class="avatar-uploader"
              :action="singleFile"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="文章简介" prop="display">
          <el-input v-model="state.articleForm.display" type="textarea"  placeholder="请输入文章简介" style="width: 40%" rows="10"/>
        </el-form-item>

        <el-form-item label="文章详细" prop="content">
          <div class="editor-container">
            <div :id="state.id"></div>
          </div>
        </el-form-item>


				<span class="dialog-footer">
					<el-button  size="default" @click="goback" >返 回</el-button>
					<el-button type="primary" size="default" @click="onSubmit">{{articleForm.id!==0?'修 改':'添 加'}}</el-button>
				</span>
    </el-form>
    </el-card>
  </div>
</template>



<script lang="ts" setup>
import {useRoute, useRouter} from 'vue-router';
import {onMounted, reactive, toRefs,onBeforeUnmount, defineComponent,ref, unref,shallowRef } from 'vue';
import {ElMessage,ElForm,ElMessageBox,UploadProps} from "element-plus";
import {addArticleList, editArticleList, getArticle} from "/@/api/system/article";
import { Plus } from '@element-plus/icons-vue'
//富文本

import wangeditor from 'wangeditor';


const route = useRoute();
const router = useRouter();
const singleFile = import.meta.env.VITE_API_URL+"/api/v1/pub/upload/singleFile";

const imageUrl = ref('')

interface ArticleFormState {
  id: number;
  title: string;
  titleUrl:string;
  display: string;
  content: string;
}

interface ArticleState {
  articleForm: ArticleFormState;
  rules:{}
}

const formRef = ref(ElForm);


// end

const state = reactive({
  articleForm: {
    id: 0,
    title: '',
    titleUrl: '',
    display: '',
    content: '',
  },
  instance:null,
  id:'wangeditor',
  editor:null as any,
  rules: {
    title: [
      { required: true, message: "标题不能为空", trigger: "blur" }
    ],
    display: [
      { required: true, message: "简介不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "文章内容不能为空", trigger: "blur" }
    ]
  }
});

const {articleForm,rules} = toRefs(state);


const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  console.log("response=",response.data.full_path);
  state.articleForm.titleUrl = import.meta.env.VITE_API_URL+"/"+response.data.path;
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/jpg') {
    ElMessage.error('上传文件的必须是jpeg,jpg,png格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('限制最大上传文件大小为 5MB!')
    return false
  }
  return true
}

function headler(){
  const id = route.query.id as string;

  console.log("article id=",id);

  if(id){
    state.articleForm.id = Number(id)
    getArticle(state.articleForm).then((rep)=>{
      state.articleForm.content = rep.data.data.content;
      state.articleForm.display = rep.data.data.display;
      state.articleForm.title = rep.data.data.title;
      state.articleForm.titleUrl = rep.data.data.titleUrl;
      imageUrl.value = rep.data.data.titleUrl;
      if(state.editor!=null) {
        state.editor.txt.html(state.articleForm.content);
      }
    })
  }

}

function goback(){
  router.go(-1);
}


// 新增/编辑
function onSubmit(){
  const formWrap = unref(formRef) as any;
  if (!formWrap) return;

  console.log(state.articleForm);
  formWrap.validate((valid: boolean) => {
    if (valid) {
      if(state.articleForm.id!==0){

        //修改
        editArticleList(state.articleForm).then(()=>{
          ElMessage.success('文章修改成功');
          //emit('dataList')
          router.push({ path: '/system/article/list' });
        })
      }else{
        //添加
        addArticleList(state.articleForm).then(()=>{
          ElMessage.success('文章添加成功');
          router.push({ path: '/system/article/list' });
          //emit('dataList')
        })
      }
    }
  });
};


//modelValue.value.openDialog(); 执行子页面方法
function initWangeditor(){
  state.editor = new wangeditor(`#${state.id}`);
  state.editor.config.fontSizes = {
    'x-small': { name: '14px', value: '14px' },
    'small': { name: '16px', value: '16px' },
    'normal': { name: '17px', value: '17px' },
    'large': { name: '18px', value: '18px' },
    'x-large': { name: '20px', value: '20px' },
    'xx-large': { name: '24px', value: '24px' },
    'xxx-large': { name: '36px', value: '16px' },
  }

  state.editor.config.zIndex = 1;
  state.editor.config.placeholder = "请输入内容...";
  state.editor.config.uploadImgShowBase64 = true;
  state.editor.config.showLinkImg = false;
  onWangeditorChange();
  state.editor.create();
  if(state.articleForm.id!=0){
    //console.log("初始化",state.articleForm.content);
    state.editor.txt.html(state.articleForm.content);
  }
  //state.editor.txt.html("");
}

function onWangeditorChange(){
  state.editor.config.onchange = (html: string) => {
    //console.log("内容改变时",html);
    state.articleForm.content = html;
  };
}

//end

onMounted(() => {
  headler()
  initWangeditor();
});


</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>